package cn.st4rlight.util.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import lombok.Getter;

/**
 * spring上下文工具类
 * NOTE: 若需要使用的话，该类必须被Spring托管
 *
 * @author st4rlight <st4rlight@163.com>
 * Created on 2024-05-04
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    // Spring容器上下文
    @Getter
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }


    /**
     * 根据名称获取Bean
     */
    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    /**
     * 根据类型获取Bean
     */
    public static <T> T getBean(Class<T> clz) {
        return applicationContext.getBean(clz);
    }
}
